<?php
    ini_set("session.gc_maxlifetime","60"); 
	session_start(); 
	// SI ESTÁ ESTA VARIABLE ES QUE YA HE INTENTADO ENVIAR UN MAIL
	$_SESSION['STATUS_TRIED'] = 1;
	
	/* Comprobamos el tiempo de sesión */
	
	if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 60)) {
		// last request was more than 30 minutes ago
		session_unset();     // unset $_SESSION variable for the run-time 
		session_destroy();   // destroy session data in storage
	}
	$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp

	/*
	You can also use an additional time stamp to regenerate the session ID periodically to avoid attacks on sessions like session fixation:
	*/
	if (!isset($_SESSION['CREATED'])) {
		$_SESSION['CREATED'] = time();
	} else if (time() - $_SESSION['CREATED'] > 60) {
		// session started more than 30 minutes ago
		session_regenerate_id(true);    // change session ID for the current session an invalidate old session ID
		$_SESSION['CREATED'] = time();  // update creation time
	}

//note that session.gc_maxlifetime should be at least equal to the life time of this custom expiration handler (1800 in this example).
	
	/* Fin comprobar tiempo de sesión */

	// Si está enviandose el mail
	if (isset($_POST['email']) && $_POST['email'] != '') { 

		// Formateamos el email
		$pEMAIL = trim($_POST['email']);
		// Si el email es correcto
		if (filter_var($pEMAIL, FILTER_VALIDATE_EMAIL)) {
			// Si todo va bien, introduzco el email en la bd
			/* INSERTAR EMAIL EN LA TABLA DE MYSQL PARA REGISTAR LAS NOTIFIACIONES */
			$con=mysqli_connect("localhost","administrador","administrador","administrador");

			// Check connection
			if (mysqli_connect_errno()) {
				$_SESSION['STATUS'] = "FAIL";
			    $_SESSION['STATUS_ERROR'] = "fatal error";
				header ("Location: index.php");
			    //echo "Failed to connect to MySQL: " . mysqli_connect_error();
			} else {
				// si todo va bien inserto
				$query = "INSERT INTO administrador.T_EMAIL_NOTIFY (NCOD_INTERNO, ADES_EMAIL) VALUES (NULL, '".$pEMAIL."');";
				$result = mysqli_query($con,$query);

				if (!$result) {
					$_SESSION['STATUS'] = "FAIL";
					$_SESSION['STATUS_ERROR'] = "fatal insertion error (".mysqli_error($con).")";
					header ("Location: index.php");
					//echo ('Database Error:' . mysql_error());
				} else {
					// si todo va bien envío el email
					require 'class.mailerautoload.php';

					$mail = new PHPMailer;

					// Aqui se ve como se configura ubuntu postfix para almacenar la contraseña en el servidir medieante certificados
					// y no almacenarlo en la web .php
					// https://rtcamp.com/tutorials/linux/ubuntu-postfix-gmail-smtp/
					// http://hluisgarcia.es/wordpress/2012/07/configurar-postfix-para-enviar-correo-desde-gmail/comment-page-1/
					
					$mail->isSMTP();                                      // Set mailer to use SMTP
					$mail->Host = 'localhost';                            // Specify main and backup SMTP servers
					//$mail->Port = 587;
					//$mail->SMTPAuth = true;                             // Enable SMTP authentication
					//$mail->Username = 'interactua.dev@gmail.com';               // SMTP username
					// Password para salir del paso
					//$mail->Password = '';                        		  // SMTP password
					$mail->SMTPSecure = 'tsl';                            // Enable encryption, 'ssl' also accepted

					$mail->From = 'interactua.dev@gmail.com';
					$mail->FromName = 'Interactua Development';
					$mail->addAddress($_POST['email']);                   // Add a recipient, nombre opcional
					$mail->addReplyTo('interactua.dev@gmail.com', 'Admin');
					//$mail->addCC('cc@example.com');
					$mail->addBCC('jneivil@gmail.com');

					
					$mail->WordWrap = 50;                                 // Set word wrap to 50 characters
					/*
					$mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
					$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name
					*/
					
					$mail->isHTML(true);                                  // Set email format to HTML

					$mail->Subject = 'Comming Soon ... ';
					$mail->AltBody = 'Next days we will launch a new application, thnks for follow us...';

					// Cuerpo del Mensaje
					$body  = "<body style='margin: 10px;'>";
					$body .= "<div style='width: 640px; font-family: Arial, Helvetica, sans-serif; font-size: 11px;'>";
					$body .= " <div align='center'>";
					// No carga la imagen, pongamos lo que pongamos hay que revisarlo, pero si carga el adjunto
					// $body .= " <img src='../../bg.jpg' /></div>";
					$body .= " <br /><br><b>Welcome to Interactua Devolopment.</b><br />";
					$body .= " Dear user, Welcome to <b>Interactua Devolopment</b>. You are one step away from having an active user account on the <b>this app</b>.";
					$body .= " <br />";
					$body .= " The details provided when you signed up were: <br />";
					$body .= " <br />";
					$body .= " <b>Username</b>: <font color='blue'>".$pEMAIL."</font><br />";
					$body .= " ";
					$body .= " In next days to activate your account, simple click on the URL below <b>before 2 hours (".date ( "d/m/Y - G:ia", (time () + (60*60*2)) ).")</b>:<br />";
					$body .= " https://... <br />";
					$body .= " <br />";
					$body .= " Either you, or someone requested an account on our system.";
					$body .= " <br />";
					$body .= " Interactua Development,<br />";
					$body .= " <a href='http://interactua.no-ip.info/'></a><br />";
					$body .= " <br />";
					$body .= "</div>";
					$body .= "</body>";
					
					$mail->AddAttachment("images/bg.jpg");
					
					$mail->Body = $body;
					
					if(!$mail->send()) {
						//echo 'Message could not be sent.';
						$_SESSION['STATUS'] = "FAIL";
						$_SESSION['STATUS_ERROR'] = "sending email fatal error";
						header ("Location: index.php");
						//echo 'Mailer Error: ' . $mail->ErrorInfo;
					} else {
						//echo 'Message has been sent';
						$_SESSION['STATUS'] = "OK";
						$_SESSION['STATUS_ERROR'] = "";
						header ("Location: ../../index_ºtruction.php");
					}
				}					
			}				
			mysqli_close($con);
			header ("Location: ../../index_construction.php");
			
			/* FIN INSERCION */	
		} else {
			$_SESSION['STATUS'] = "FAIL";
			$_SESSION['STATUS_ERROR'] = "incorrect email";
			header ("Location: ../../index_construction.php");
		}
	} else {
		$_SESSION['STATUS'] = "FAIL";
		$_SESSION['STATUS_ERROR'] = "introduce your email";
		header ("Location: ../../index_construction.php");
	}
	//echo $_SESSION['STATUS']."<br />";
	//echo $_SESSION['STATUS_ERROR']."<br />";
 ?>
